package com.anydata.android.weatherforecast.weather.webservice;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URLEncoder;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.util.Log;

import com.anydata.android.weatherforecast.weather.GoogleWeatherHandler;
import com.anydata.android.weatherforecast.weather.WeatherSet;
import com.anydata.android.widget.weatherclock.ConstData;


public class WeatherForecastService {
	
	
	public static final String TAG = "ForecastService";
	
	private static HttpClient sClient = new DefaultHttpClient();
	
	public WeatherSet getForecasts(String cityParam) throws ParseException {
		
		String cityParamString = "39930000,116279998";  
		
		if(cityParam == null || "".equals(cityParam.trim())){
			cityParam = cityParamString;
		}
		
		String urlStr = ConstData.queryString + URLEncoder.encode(cityParam);
		
		WeatherSet ws = null;
        Reader reader = null;
        HttpGet request = new HttpGet(urlStr);
        request.setHeader("User-Agent", "Android Google");

        try {
        	SAXParserFactory spf = SAXParserFactory.newInstance(); 
            SAXParser sp = spf.newSAXParser(); 

            XMLReader xr = sp.getXMLReader();
            
            GoogleWeatherHandler gwHandler = new GoogleWeatherHandler(); 
            xr.setContentHandler(gwHandler); 
            HttpResponse response = sClient.execute(request);

            StatusLine status = response.getStatusLine();
            Log.d(TAG, "Request returned status " + status);

            HttpEntity entity = response.getEntity();
            reader = new InputStreamReader(entity.getContent(), "GBK");
            InputSource is=new InputSource(reader);
            xr.parse(is);
            
            ws = gwHandler.getWeatherSet();
            
        } catch (IOException e) {
        	
            throw new ParseException("Problem calling forecast API", e);
        } catch (SAXException e) {
        	
        	throw new ParseException("Problem calling forecast API when parsing", e);
		} catch (ParserConfigurationException e) {
			
        	throw new ParseException("Problem calling forecast API when parsing", e);
		}
        
        return ws;
		
}

}
